//
//  CLNavigationController.m
//  Charles
//
//  Created by Leo on 2017/5/22.
//  Copyright © 2017年 charles. All rights reserved.
//

#import "CLNavigationController.h"

#define KEY_WINDOW  [[UIApplication sharedApplication]keyWindow]


@interface CLNavigationController ()<UIGestureRecognizerDelegate> {
    
    CGPoint _startPoint;
    UIImageView *_lastScreenShotView;
    UIImageView *_shadowImage;
    NSInteger _mainScreenHeight;
    NSInteger _mainScreenWidth;
    UIPanGestureRecognizer *_panRecognizer;
}

@property (nonatomic, strong) UIView *backGroundView;
@property (nonatomic, retain) NSMutableArray *screenShotList;
@property (nonatomic, assign) BOOL isMoving;

@end

static const CGFloat offset_float = 0.65;   // 拉伸参数
static const CGFloat min_distance = 100;    // 最小回弹距离

@implementation CLNavigationController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpData];
    [self setUpView];
}

- (void)setUpData {
    _mainScreenHeight = SCREEN_HEIGHT;
    _mainScreenWidth = SCREEN_WIDTH;
    self.screenShotList = [[NSMutableArray alloc]initWithCapacity:0];
}


- (void)setUpView {
    _panRecognizer = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panGestureRecognizer:)];
    [_panRecognizer delaysTouchesBegan];
    _panRecognizer.delegate = self;
    
    self.canDragBack = YES;

    _shadowImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"leftside_shadow_bg"]];
    _shadowImage.alpha = 0.8;
    _shadowImage.frame = CGRectMake(-10, 0, 10, SCREEN_HEIGHT);
    [self.view addSubview:_shadowImage];

    UIImage *image = [UIImage imageNamed:@"nav_bg"];
    UIImage *resizeImage = [image resizableImageWithCapInsets:UIEdgeInsetsMake(5, 5, 5, 5) resizingMode:UIImageResizingModeStretch];
    [self.navigationBar setBackgroundImage:resizeImage forBarMetrics:UIBarMetricsDefault];

    
}

- (NSMutableArray *)screenShotList {
    if (_screenShotList == nil) {
        _screenShotList =[[NSMutableArray alloc]initWithCapacity:0];
    }
    return _screenShotList;
}

- (void)setCanDragBack:(BOOL)canDragBack {
    _canDragBack = canDragBack;
    if (_panRecognizer) {
        if (_canDragBack == NO) {
            [_panRecognizer removeTarget:self action:@selector(panGestureRecognizer:)];
            [self.view removeGestureRecognizer:_panRecognizer];
        }else {
            [_panRecognizer addTarget:self action:@selector(panGestureRecognizer:)];
            [self.view addGestureRecognizer:_panRecognizer];
        }
    }
}

-(void)panGestureRecognizer:(UIGestureRecognizer *)recognizer {
    if (self.viewControllers.count <= 1 || !self.canDragBack) return;
    
    CGPoint touchPoint = [recognizer locationInView:KEY_WINDOW];
    
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        _isMoving = YES;
        _startPoint = touchPoint;
        CGRect frame = self.view.frame;
        if (!_backGroundView) {
            _backGroundView = [[UIView alloc]init];
            _backGroundView.backgroundColor = [UIColor whiteColor];
        }
        
        _backGroundView.frame = CGRectMake(0, 0, frame.size.width , frame.size.height);
        
        [self.view.superview insertSubview:self.backGroundView belowSubview:self.view];
        
        _backGroundView.hidden = NO;
        
        if (_lastScreenShotView) [_lastScreenShotView removeFromSuperview];
        
        UIImage *lastScreenShot = [self.screenShotList lastObject];
        
        _lastScreenShotView = [[UIImageView alloc] initWithImage:lastScreenShot];
        
        _lastScreenShotView.frame = (CGRect){-(_mainScreenWidth*offset_float),0,SCREEN_WIDTH,_mainScreenHeight};
        
        [self.backGroundView addSubview:_lastScreenShotView];
        
        //End paning, always check that if it should move right or move left automatically
    }else if (recognizer.state == UIGestureRecognizerStateEnded){
        
        if (touchPoint.x - _startPoint.x > min_distance)
        {
            [UIView animateWithDuration:0.3 animations:^{
                
                [self moveViewWithOffsetX:_mainScreenWidth];
                
            } completion:^(BOOL finished) {
                
                id lastVC = self.viewControllers.lastObject;
                if ([lastVC isKindOfClass:[CLBaseViewController class]]) {
                    CLBaseViewController *srVC = (CLBaseViewController *)lastVC;
                    if ([srVC respondsToSelector:@selector(backGestureAction)]) {
                        [srVC backGestureAction];
                    }
                }
                
                [self gestureAnimation:NO];
                
                CGRect frame = self.view.frame;
                
                frame.origin.x = 0;
                
                self.view.frame = frame;
                
                _isMoving = NO;
                if (_lastScreenShotView) [_lastScreenShotView removeFromSuperview];
            }];
        }
        else
        {
            [UIView animateWithDuration:0.3 animations:^{
                [self moveViewWithOffsetX:0];
            } completion:^(BOOL finished) {
                _isMoving = NO;
                
                self.backGroundView.hidden = YES;
                if (_lastScreenShotView) [_lastScreenShotView removeFromSuperview];
            }];
        }
        
        return;
    }else if (recognizer.state == UIGestureRecognizerStateCancelled){
        
        [UIView animateWithDuration:0.3 animations:^{
            [self moveViewWithOffsetX:0];
        } completion:^(BOOL finished) {
            _isMoving = NO;
            if (_lastScreenShotView) [_lastScreenShotView removeFromSuperview];
            self.backGroundView.hidden = YES;
        }];
        
        return;
    }
    if (_isMoving) {
        [self moveViewWithOffsetX:touchPoint.x - _startPoint.x];
    }
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    return ![touch.view isKindOfClass:NSClassFromString(@"SVSegmentedControl")];
}

#pragma mark - 重写Pop,Push 方法

- (UIViewController *)popViewControllerAnimated:(BOOL)animated {
    if (self.screenShotList.count) {
        [self.screenShotList removeAllObjects];
    }
    return [super popViewControllerAnimated:animated];
}

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
    UIImage *image = [self captureScreen];
    if (self.screenShotList && image) {
        [self.screenShotList addObject:image];
    }
    [super pushViewController:viewController animated:animated];
}

#pragma mark - 一些方法

- (UIImage *)captureScreen {
    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, self.view.opaque, 0.0);
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

- (void)moveViewWithOffsetX:(CGFloat)offsetX {
    offsetX = offsetX>SCREEN_WIDTH?SCREEN_WIDTH:offsetX;
    offsetX = offsetX<0?0:offsetX;
    CGRect frame = self.view.frame;
    frame.origin.x = offsetX;
    self.view.frame = frame;
    _lastScreenShotView.frame = (CGRect) { -(_mainScreenWidth * offset_float) + offsetX * offset_float,0,SCREEN_WIDTH,_mainScreenHeight};
}

- (void)gestureAnimation:(BOOL)animated {
    [self.screenShotList removeLastObject];
    [super popViewControllerAnimated:animated];
}

- (void)removeLastPageScreen{
    if (_screenShotList.count) {
        [_screenShotList removeLastObject];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
